/*
 * @Description:
 * @Author: Evan.Zhang
 * @Date: 2022-07-08 11:24:37
 * @LastEditTime: 2022-08-09 13:41:23
 * @LastEditors: Evan.Zhang
 * @Reference:
 */

/**
 * @description: 不允许内部直接关闭
 * @return {*}
 */
self.close = function () {
  self.postMessage({TerminateThis:true});
}


/**
 * @description: 注入局部对象到作用域
 * @return {*}
 * @param {*} scopeObject:局部对象
 */
function injectScopeVariable2This(scopeObject = {}) {
  const changedAttrs = [];
  Object.keys(scopeObject).forEach((key) => {
    if (this[key]) return;
    changedAttrs.push(key)
    this[key] = scopeObject[key]
  })
  // 恢复
  return () => {
    changedAttrs.forEach(key => delete this[key])
  }
}


/**
 * @description: 初始化线程任务
 * @return {*}
 * @param {*} JSFile
 */
function execution(JSFile, args) {
  // 通知
  this.postMessage({ TheThreadRunningState: true });
  let rollbackInject = undefined;
  try {
    rollbackInject = injectScopeVariable2This.call(this, args);
    // 执行
    Function(JSFile).call(this, args);
  } catch (error) {
    console.error("The thread has a ERROR INFO>>>:", error,"The thread running CODE IS>>>:", JSFile);
  } finally {
    // 回滚注入
    rollbackInject && rollbackInject();
  }
  // 通知
  this.postMessage({TheThreadRunningState:false});
}

/**
 * @description: 代码接受器
 * @return {*}
 * @param {*} message
 * @param {*} function
 */
self.addEventListener('message', function (e) {
  let { jsFile, args } = e.data
  execution(jsFile,args);
}, false);
